<script lang="ts" setup>
import { h, ref, reactive } from 'vue'
import { useResetReactive } from 'dsrz/hooks/useReset'
import { aesEncrypt, createRef, refs } from 'dsrz/utils'

import CurrencyDemo from '@/components/demo/index.vue'

import type { ColumnItem, Params } from './types'

// 定义表单数据类型
interface FormDetails {
  deptId?: string
  name?: string
  code?: string
  userId?: string
  phone?: string
  enable?: number
  file?: any
}

defineOptions({
  name: 'CurrencyTablePage',
})

const {
  params,
  exposes: { reset },
} = useResetReactive({})

const data = ref([
  {
    jc: '基础22',
    encrypt: aesEncrypt('加密'),
    decrypt: aesEncrypt('解密'),
    epmb: 'element-plus模板',
    dsrzmb: 'dsrz模板',
    h1: 'h(简单):modelValue',
    h2: 'h(简单):backups',
    h3: 'h(复杂)',
  },
])

const items = ref([
  {
    prop: 'srk',
    is: 'currency-input',
    bind: {
      placeholder: '专业名称',
      clearable: true,
    },
  },
  {
    prop: 'jmsrk',
    is: 'currency-input',
    display: ({ show }: Params) => show === 1,
    isEncrypt: true,
    bind: {
      placeholder: '输入框(加密)',
      clearable: true,
    },
  },
  {
    prop: 'epxlk',
    is: 'el-select-v2',
    bind: {
      options: [
        { label: '选项1', value: '1' },
        { label: '选项2', value: '2' },
      ],
      placeholder: '状态',
      clearable: true,
    },
  },
  {
    prop: 'show',
    is: 'el-select-v2',
    bind: {
      options: [
        { label: '是', value: 1 },
        { label: '否', value: 0 },
      ],
      placeholder: 'display使用',
      clearable: true,
    },
  },
  {
    prop: 'dsrzxlk',
    is: 'currency-select',
    bind: {
      request: () => [
        { id: '选项1', name: '1' },
        { id: '选项2', name: '2' },
      ],
      props: { label: 'name', value: 'id' },
      placeholder: 'dsrz下拉框',
      clearable: true,
    },
  },
  {
    prop: 'date',
    is: 'el-date-picker',
    queryValue: ['startDate', 'endDate'],
    joinValue: ['00:00:00', '23:59:59'],
    bind: {
      type: 'daterange',
      startPlaceholder: '开始日期',
      endPlaceholder: '结束日期',
      valueFormat: 'YYYY-MM-DD',
      clearable: true,
    },
  },
  {
    is: 'currency-button',
    bind: {
      color: '#6f6f6f',
      title: '清空',
      icon: 'DsrzClear',
    },
    on: { click: reset },
  },
])

const btns = ref([
  {
    is: 'currency-button',
    bind: {
      color: '#178782',
      title: '导入专业',
      icon: 'DsrzExport',
    },
    on: {
      click: () => {
        resetForm() // 重置表单
        openDialog()
        dialogTitle.value = '导入专业'
        dialogType.value = 'import'
      },
    },
  },
  {
    is: 'currency-button',
    bind: {
      color: '#178782',
      title: '下载导入模版',
      icon: 'DsrzExport',
    },
    on: {
      click: () => {
       console.log('== 下载导入模版')
      },
    },
  },
  {
    is: 'currency-button',
    bind: {
      type: 'primary',
      title: '新增',
      icon: 'DsrzAdd',
    },
    on: {
      click: () => {
        resetForm() // 重置表单并设置默认值
        openDialog()
        dialogTitle.value = '新增专业'
        dialogType.value = 'add'
      },
    },
  },
])

const columns = ref([
  // { type: 'selection', width: '55px' },
  { label: '序号', type: 'index' },
  {
    label: '加密',
    prop: 'encrypt',
    display: ({ show }: Params) => show === 1,
  },
  { label: '所属二级学院', prop: 'decrypt', isDecrypt: true },
  { label: '专业名称', prop: 'epmb', is: 'el-input' },
  { label: '专业代码', prop: 'dsrzmb', is: 'currency-input' },
  {
    label: '创建时间',
    prop: 'h1',
    is: ({ modelValue }: ColumnItem) =>
      h('span', { style: { color: 'red' } }, modelValue),
  },
  {
    label: '负责人',
    prop: 'h2',
    is: ({ backups }: ColumnItem) => h('span', backups.h2),
  },
  { label: '手机号', prop: 'h2', is: h(CurrencyDemo) },
  { label: '手机号', prop: 'h2', is: h(CurrencyDemo) },


  
  {
    label: '操作(基础) <=3',
    is: 'currency-more',
    list: [
      {
        is: 'currency-button',
        bind: { type: 'primary', link: true, title: '编辑1a' },
      },
      {
        is: 'currency-button',
        bind: { type: 'primary', link: true, title: '编辑2b' },
      },
      {
        is: 'currency-button',
        bind: { type: 'primary', link: true, title: '编辑3c' },
      },
    ],
  },
  {
    label: '操作(更多) > 3',
    is: 'currency-more',
    list: [
      {
        is: 'currency-button',
        bind: { type: 'primary', link: true, title: '编辑1c' },
      },
      {
        is: 'currency-button',
        bind: { type: 'primary', link: true, title: '编辑2' },
      },
      {
        is: 'currency-button',
        bind: { type: 'primary', link: true, title: '编辑3' },
      },
      {
        is: 'currency-button',
        bind: { type: 'primary', link: true, title: '编辑4' },
      },
      {
        is: 'currency-button',
        bind: { type: 'primary', link: true, title: '编辑5' },
      },
    ],
  },
])


const openDialog = () => {
  Object.assign(form, { visible: true, })
}

const resetForm = () => {
  Object.assign(form, { 
    details: { enable: 1 } as FormDetails // 重置表单，设置默认值
  })
}
const dialogTitle = ref<string>('')
const dialogType = ref<'import' | 'add'>('add') // 对话框类型：import-导入，add-新增

const form = reactive({
  visible: false,
  size: 'default',
  details: {} as FormDetails,
  items: [
    {
      label: '所属二级学院',
      prop: 'deptId',
      is: 'currency-select',
      display: true, // 导入和新增都显示
      bind: {
        clearable: true,
        placeholder: '请选择所属二级学院',
        options: [
          { label: '选项1', value: '1' },
          { label: '选项2', value: '2' },
        ],
      },
    },
    {
      label: '专业名称',
      prop: 'name',
      is: 'el-input',
      display: (value: any, row: any) => dialogType.value === 'add', // 只有新增时显示
      bind: {
        placeholder: '请输入专业名称',
      },
    },
    {
      label: '专业代码',
      prop: 'code',
      is: 'el-input',
      display: (value: any, row: any) => dialogType.value === 'add', // 只有新增时显示
      bind: {
        placeholder: '请输入专业代码',
      },
    },
    {
      label: '负责人',
      prop: 'userId',
      is: 'currency-select',
      display: (value: any, row: any) => dialogType.value === 'add', // 只有新增时显示
      bind: {
        clearable: true,
        placeholder: '请选择负责人',
        options: [
          { label: '负责人1', value: 'fz-1' },
          { label: '负责人2', value: 'fz-2' },
        ],
      },
      on: {
        change: (value: string) => {
          console.log('===  负责人', value)
          // 根据负责人设置对应的手机号
          const phoneMap: Record<string, string> = {
            'fz-1': '12345678914',  // 负责人1的手机号
            'fz-2': '13888888888',  // 负责人2的手机号
          }
          form.details.phone = phoneMap[value] || ''
        }
      }
    },
    {
      label: '手机号',
      prop: 'phone',
      is: 'el-input',
      display: (value: any, row: any) => dialogType.value === 'add', // 只有新增时显示
      bind: {
        placeholder: '请输入手机号',
        disabled: true,
      },
    },
    {
      label: '状态',
      prop: 'enable',
      is: 'currency-radio',
      display: (value: any, row: any) => dialogType.value === 'add', // 只有新增时显示
      bind: {
        placeholder: '请选择状态',
        options: [
          { label: '启用', value: 1 },
          { label: '禁用', value: 0 },
        ],
      },
    },
    {
      label: '选择文件',
      prop: 'file',
      is: 'currency-upload',
      display: (value: any, row: any) => dialogType.value === 'import', // 只有导入时显示
      bind: {
        'auto-upload': false,
        action: '#',
        limit: 1,
        accept: '.xlsx,.xls',
        buttonTitle: '选择文件',
      },
    },

  ],
  rules: {
    deptId: [{ required: true, message: '请选择所属二级学院', trigger: 'blur' }],
    name: [{ required: true, message: '请输入专业名称', trigger: 'blur' }],
    code: [{ required: true, message: '请输入专业代码', trigger: 'blur' }],
    userId: [{ required: true, message: '请选择负责人', trigger: 'blur' }],
    phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
    enable: [{ required: true, message: '请选择状态', trigger: 'blur' }],
  },
})

const handleConfirm = async () => {
  // 通过全局 refs 访问表单实例
  const formInstance = refs.formRef
  
  if (formInstance) {
    // 触发表单验证
    const isValid = await formInstance.validate()
    if (isValid) {
      // 验证通过，执行确认逻辑
      console.log('表单验证通过', form.details)
      form.visible = false
    } else {


      // 验证失败
      console.log('表单验证失败')
      return false // 阻止对话框关闭
    }
  } else {
    console.log('表单实例未找到')
    return false
  }
}

</script>
<template>
  <div>
    <CurrencyTable
      :data="data"
      :params="params"
      :items="items"
      :btns="btns"
      :columns="columns"
    />
  </div>

  <div>
    <CurrencyDialog
      v-model="form.visible"
      :title="dialogTitle"
      :size="form.size"
      @cancel="form.visible = false"
      @confirm="handleConfirm"
      >
      <CurrencyForm
        ref="formRef"
        v-model="form.details"
        :items="form.items"
        :rules="form.rules"
        label-position="top"
      />
    </CurrencyDialog>
  </div>
  
</template>
